<template>
	<div style="display: -webkit-box;">
		<ul class="nav nav-list cascader-dropdown-item">
			<cascade-item v-for="item in data" :data="item" :key="item" :setVal="setVal"
						  @click.native.stop="handleClickItem(item)">
			</cascade-item>
		</ul>
		<cascade-panel v-if="sublist && sublist.length" :data="sublist"></cascade-panel>
	</div>
</template>

<script>
	import CascadeItem from './CascadeItem.vue';
	import Emitter from './emitter';
	export default {
		name: 'CascadePanel',
		mixins: [Emitter],
		components: {CascadeItem},
		data () {
			return {
				sublist: [],
				setVal: {}
			};
		},
		props: {
			data: {type: Array}
		},
		watch: {
			data: function () {
				this.setVal = {};
				this.sublist = [];
			}
		},
		methods: {
			handleClickItem (item) {
				if (item.disabled) return;
				this.handleTriggerItem(item);
			},
			findComponentUpward (context, componentName, componentNames) {
				if (typeof componentName === 'string') {
					componentNames = [componentName];
				} else {
					componentNames = componentName;
				}

				let parent = context.$parent;
				let name = parent.$options.name;
				while (parent && (!name || componentNames.indexOf(name) < 0)) {
					parent = parent.$parent;
					if (parent) name = parent.$options.name;
				}
				return parent;
			},
			handleTriggerItem (item) {
				if (item.loading !== undefined && !item.children.length) {
					const cascader = this.findComponentUpward(this, 'CascadeSelector');
					if (cascader && cascader.loadData) {
						item.loading = true;
						cascader.loadData(item, () => {
							this.handleTriggerItem(item);
						});
						return;
					}
				}
				let backUp = this.getBaseItem(item);
				this.setVal = backUp;
				this.emitUpdate([backUp]);
				if (item.children !== undefined) {
					this.sublist = item.children;
				} else {
					this.dispatch('CascadeSelector', 'on-select-end');
				}
			},
			getBaseItem (item) {
				let backUp = Object.assign({}, item);
				if (backUp.children) {
					delete backUp.children;
				}
				return backUp;
			},
			updateResult (item) {
				this.result = [this.setVal].concat(item);
				this.emitUpdate(this.result);
			},
			emitUpdate (result) {
				if (this.$parent.$options.name === 'CascadePanel') {
					this.$parent.updateResult(result);
				} else {
					this.$parent.$parent.updateResult(result);
				}
			}
		},
		mounted () {
			this.$on('on-clear', () => {
				this.sublist = [];
				this.setVal = {};
			});
		}
	};
</script>
